package com.itcoon.cloud.framework.security.handler;

import com.itcoon.cloud.framework.security.model.AuthToken;
import com.itcoon.cloud.framework.security.utils.AuthTokenUtil;
import com.itcoon.cloud.framework.security.utils.JwtTokenUtil;
import com.itcoon.cloud.framework.webmvc.response.ApiResponse;
import com.itcoon.cloud.framework.webmvc.utils.ApiResponseUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author Administrator
 * created in 2021/4/29
 */
public class TokenLogoutHandler implements LogoutHandler{

	private static final Logger log = LoggerFactory.getLogger(TokenLogoutHandler.class);
	private static final String AUTH_HEADER_NAME = "Authorization";
	private static final String AUTH_BASIC_PREFIX = "Basic ";
	private static final String AUTH_API_PREFIX = "Bearer ";


	@Override
	public void logout(HttpServletRequest request, HttpServletResponse response, Authentication authentication) {
		String token = request.getHeader(AUTH_HEADER_NAME);
		try {
			if (token != null) {
				if (token.startsWith(AUTH_BASIC_PREFIX)) {
					String accessToken = token.substring(AUTH_BASIC_PREFIX.length());
					Long userId = JwtTokenUtil.getUserIdFromAccessToken(accessToken);
					AuthTokenUtil.removeTokenByKey(userId);
					return;
				}
				if (token.startsWith(AUTH_API_PREFIX)) {
					token = token.substring(AUTH_API_PREFIX.length());
				}
				Long userId = JwtTokenUtil.getUserIdFromAccessToken(token);
				AuthToken authToken = AuthTokenUtil.getToken(userId);
				if (authToken != null) {
					AuthTokenUtil.removeTokenByKey(userId);
					log.info("Successfully remove token from redis, key = {}", userId + "");
				}
			}
		}catch (Exception e){
			log.error(e.getMessage(), e);
			ApiResponseUtils.writeJsonResponse(response, ApiResponse.error(), HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
		}
	}

}
